from flask import Flask, render_template, request, jsonify
from models import Stock, Industry
from data_loader import load_data_from_akshare  # 使用之前修改的API数据加载函数
from data_loader import get_stock_total, get_stock_list,save_to_sqlite

app = Flask(__name__)

# 从API加载数据
stocks, industries = load_data_from_akshare()

@app.route('/')
def index():
    # 获取所有行业及其股票数量
    industry_stats = {}
    for industry_name, industry in industries.items():
        industry_stats[industry_name] = len(industry.stocks)
    
    return render_template('index.html', industries=industries, industry_stats=industry_stats)

@app.route('/industry/<industry_name>')
def industry_detail(industry_name):
    if industry_name in industries:
        industry = industries[industry_name]
        return render_template('industry.html', industry=industry)
    return "行业不存在", 404

@app.route('/api/search')
def search():
    query = request.args.get('query', '')
    results = []
    
    # 如果查询为空，返回所有行业
    if not query:
        for name, industry in industries.items():
            results.append({
                'name': name,
                'count': len(industry.stocks)
            })
    else:
        # 搜索匹配的行业
        for name, industry in industries.items():
            if query.lower() in name.lower():
                results.append({
                    'name': name,
                    'count': len(industry.stocks)
                })
    
    return jsonify(results)

# 新增：按股票代码或名称搜索
@app.route('/api/search_stock')
def search_stock():
    query = request.args.get('query', '')
    industry_filter = request.args.get('industry', '')
    results = []
    
    # 如果有行业过滤条件
    if industry_filter and industry_filter in industries:
        industry = industries[industry_filter]
        for stock in industry.stocks:
            if query.lower() in stock.code.lower() or query.lower() in stock.name.lower():
                results.append(stock.to_dict())
    # 如果没有行业过滤，在所有股票中搜索
    elif query:
        for stock in stocks:
            if query.lower() in stock.code.lower() or query.lower() in stock.name.lower():
                results.append(stock.to_dict())
    
    return jsonify(results)


@app.route('/api/stock_count')
def stock_count():
    total = get_stock_total()
    return jsonify({'total': total})

@app.route('/api/stock_list')
def stock_list():
    stocks = get_stock_list()
    return jsonify({'stocks': stocks})

# 同步完成
@app.route('/api/sync_stocks')
def sync_stocks():
    success = save_to_sqlite()
    return {'success': success, 'message': '同步完成' if success else '同步失败'}


if __name__ == '__main__':
    print("正在初始化数据库并同步股票数据...")
    save_to_sqlite() # 在应用启动时执行一次数据同步
    print("数据库初始化完成。")
    app.run(debug=True)